﻿using B.S.BaseData.Infrastructure.Implements;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.ProcessEgine.API.Extensions;
using B.S.ProcessEgine.API.Untils;
using B.S.ProcessEgine.Infractructure.Implements;
using B.S.ProcessEgine.Infractructure.Interfaces;
using Microsoft.EntityFrameworkCore;

/// <summary>
/// 服务拓展类
/// </summary>
public static class ServiceCollectionExtensions
{
    /// <summary>
    /// 注册数据库
    /// </summary>
    /// <typeparam name="TDbContext"></typeparam>
    /// <param name="services"></param>
    /// <param name="connectionString"></param>
    /// <param name="enableSqlLog"></param>
    /// <returns></returns>
    public static IServiceCollection AddDbContextService<TDbContext>(this IServiceCollection services, string? connectionString, bool enableSqlLog) where TDbContext : DbContext
    {
        return services.AddDbContext<TDbContext>(builder =>
        {
            //用到事务需要把重试策略删掉
            builder.UseSqlServer(connectionString!).EnableSensitiveDataLogging();

            if (enableSqlLog)
                builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                {
                    configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();
                }));
         
        });
    }

    public static IServiceCollection AddServices(this IServiceCollection services)
    {
        //仓储层注入
        services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));

        //注入表单分类仓储
        services.AddScoped<IFormTypeRepository, FormTypeRepository>();

        //注入行业分类仓储
        services.AddScoped<IGirdProfessionalRepository, GirdProfessionalRepository>();
        
        //注入表单仓储
        services.AddScoped<IFormInfoRepository, FormInfoRepository>();

         //注入表单字段（字段属性表）仓储
        services.AddScoped<IFormInfoDetailRepository, FormInfoDetailRepository>();

        //注入表单节点 仓储
        services.AddScoped<IFormNodeRepository, FormNodeRepository>();

        //注入AutoMapper
        services.AddAutoMapper(typeof(MapperProFiles));

        //注入全局异常处理
         services.AddControllers(x => x.Filters.Add<GlobalExceptionFilter>());

        //大小写转换
        services.AddControllers().AddJsonOptions(d => d.JsonSerializerOptions.PropertyNamingPolicy = null);

        return services;
    }
}